﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Runtime;
using ACADApplication= Autodesk.AutoCAD.ApplicationServices.Application;
using ACADDatabase=Autodesk.AutoCAD.DatabaseServices.Database;
using ACADDocument=Autodesk.AutoCAD.ApplicationServices.Document;
using System.Collections;

namespace YNCNumberSys
{
    /// <summary>
    /// 通过选择外部文件,向图纸总插入块表记录.
    /// </summary>
    class ZJInsertBlockTableRecord
    {
        #region 数据变量
        /// <summary>
        /// 块名.
        /// </summary>
        private string _str_BlockName;
        /// <summary>
        /// 块在本地的全文件路径.
        /// </summary>
        private string _str_BlockPath;
        /// <summary>
        /// 返回值,块的对象标识符号.
        /// </summary>
        private ObjectId _id_BlockTableRecord;
        /// <summary>
        /// 事务,为空表示操作当前图纸空间.
        /// </summary>
        private Transaction _trs_Transaction;
        /// <summary>
        /// 图纸文档WorkingDatabase,为空表示当前的图纸空间.
        /// </summary>
        private ACADDatabase _wdb_DataBase;
        /// <summary>
        /// 图纸文档,为空表示当前的激活的图纸文档.
        /// </summary>
        private ACADDocument _doc_MdiActiveDocument;
        /// <summary>
        /// 该值如果为True,则(1)_trs_Transaction,_wdb_DataBase和图纸文档均为当前图纸空间,并且图纸文档未锁定;
        /// (2)事务提交在该类内完成.
        /// </summary>
        private bool _b_TransactionIsUsed;
        #endregion

        public ZJInsertBlockTableRecord(ACADDatabase wdb_DataBase, 
            ACADDocument doc_MdiActiveDocument,Transaction trs_Transaction, string str_BlockName, string str_BlockPath)
        {
            _wdb_DataBase = wdb_DataBase;
            _doc_MdiActiveDocument = doc_MdiActiveDocument;
            _trs_Transaction = trs_Transaction;
            _str_BlockName=str_BlockName;
            _str_BlockPath=str_BlockPath;
            _b_TransactionIsUsed = true;
        }
        public ZJInsertBlockTableRecord(string str_BlockName, string str_BlockPath)
        {
            _wdb_DataBase = HostApplicationServices.WorkingDatabase;
            _doc_MdiActiveDocument = ACADApplication.DocumentManager.MdiActiveDocument;
            _trs_Transaction = null;
            _str_BlockName = str_BlockName;
            _str_BlockPath = str_BlockPath;
            _b_TransactionIsUsed = false;
        }
        /// <summary>
        /// 插入到当前图纸中的块对象句柄
        /// </summary>
        public ObjectId id_BlockTableRecord
	    {
		    get { return _id_BlockTableRecord; }
		    set { _id_BlockTableRecord = value; }
	    }
        private void DoInsertBlockTableRecord()
        {
            if (!_b_TransactionIsUsed)
            {
                _trs_Transaction = _wdb_DataBase.TransactionManager.StartTransaction();
            }
            /*
            BlockTable bt = (BlockTable)_trs_Transaction.GetObject(_wdb_DataBase.BlockTableId, OpenMode.ForRead);
            if (bt.Has(_str_BlockName))
            {
               
               IEnumerator btEmu = bt.GetEnumerator();
               while (btEmu.MoveNext())
               {
                   ObjectId btrId = (ObjectId)btEmu.Current;

                   BlockTableRecord btr = (BlockTableRecord)_trs_Transaction.GetObject(btrId, OpenMode.ForRead);
                   if (btr.Name == _str_BlockName)
                   {
                       _id_BlockTableRecord = btr.ObjectId;
                   }
                  
               }

               if (!_b_TransactionIsUsed)
               {
                   _trs_Transaction.Dispose();
               }
               return;
            }
            */
            

            //ACADDatabase db_TempDB = new ACADDatabase();
            //db_TempDB.ReadDwgFile(_str_BlockPath, System.IO.FileShare.None, true, null);//FileOpenMode.OpenForReadAndAllShare, false, null);

            ACADDatabase db_TempDB = new ACADDatabase(false,true);
            db_TempDB.ReadDwgFile(_str_BlockPath, FileOpenMode.OpenForReadAndAllShare, false, null);//

            db_TempDB.CloseInput(true);
            //ObjectIdCollection objId_Collection = new ObjectIdCollection();
            //ACADDatabase cls_TempBlockDB = new ACADDatabase();
            //using (Transaction tr = db_TempDB.TransactionManager.StartTransaction())
            //{
            //    try
            //    {
            //        BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db_TempDB.CurrentSpaceId, OpenMode.ForRead);
                    
            //        foreach (ObjectId id in btr)
            //        {
            //            objId_Collection.Add(id);
            //        }
            //        db_TempDB.Wblock(cls_TempBlockDB, objId_Collection, Point3d.Origin, DuplicateRecordCloning.Ignore);
            //        tr.Commit();
            //        tr.Dispose();
            //    }
            //    catch (Autodesk.AutoCAD.Runtime.Exception ex)
            //    {
            //        tr.Dispose();
            //        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message);
            //    }
            //}
            
            try
            {
                _id_BlockTableRecord = _wdb_DataBase.Insert(BlockTableRecord.ModelSpace, _str_BlockName, db_TempDB, false);
                if (!_b_TransactionIsUsed)
                {
                    _trs_Transaction.Commit();
                    _trs_Transaction.Dispose();
                }
            }
            catch
            {
                if (!_b_TransactionIsUsed)
                {
                    _trs_Transaction.Dispose();
                }
            }
            //cls_TempBlockDB.Dispose();
            db_TempDB.Dispose();
        }
        /// <summary>
        /// 执行块插入操作,返回插入块句柄,如果块文件不存在或者插入失败,返回ObjectId.Null.
        /// </summary>
        /// <returns>块句柄或ObjectId.Null</returns>
        public ObjectId Do()
        {
            _id_BlockTableRecord = ObjectId.Null;
            if (!System.IO.File.Exists(_str_BlockPath))
            {
                _doc_MdiActiveDocument.Editor.WriteMessage(string.Format("\n块文件:{0} 不存在!", _str_BlockPath));
                return _id_BlockTableRecord;
            }
            if (!_b_TransactionIsUsed)
            {
                using (_doc_MdiActiveDocument.LockDocument())
                {
                    DoInsertBlockTableRecord();
                }
            }
            else
            {
                DoInsertBlockTableRecord();
            }
            return _id_BlockTableRecord;
        }
    }
}
